package edu.bu.cs673.superkids123.children.DataObjectAccess;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import edu.bu.cs673.superkids123.HibernateUtil;
import edu.bu.cs673.superkids123.children.model.PlayTime;
import edu.bu.cs673.superkids123.common.model.Child;

public class PlayTimeManager {

	public static List<PlayTime> getPlayTime(Child child, Date date) {
		List<PlayTime> playTimes = null;
		Transaction tx = null;
		Session session = HibernateUtil.getSessionFactory().openSession();

		try {
			tx = session.beginTransaction();
			Criteria criteria = session.createCriteria(PlayTime.class);

			if (date != null) {
				criteria.add(Restrictions.eq("child", child));
				criteria.add(Restrictions.ge("datePlayed", date));
			} else {
				criteria.add(Restrictions.eq("child", child));
			}

			playTimes = criteria.list();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}

		return playTimes;
	}

	public static void addPlayTime(Child child, int timePlayed) {
		Transaction tx = null;
		Session session = HibernateUtil.getSessionFactory().openSession();

		try {

			tx = session.beginTransaction();

			PlayTime playTime = new PlayTime();
			playTime.setDatePlayed(new Date());
			playTime.setTimePlayed(timePlayed);
			playTime.setChild(child);

			session.save(playTime);

			session.getTransaction().commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
}
